package com.project;

import com.project.config.WebMvcConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;

public class Main3 {

    public Main3(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();

        Context ctx = tomcat.addContext("",null);
        WebApplicationContext wac = createApplicationContext(ctx.getServletContext());
        //创建前端控制器对象
        DispatcherServlet dis = new DispatcherServlet(wac);
        //注册前端控制器
        Wrapper wrp =  Tomcat.addServlet(ctx,"dis",dis);
        wrp.setLoadOnStartup(0);
        wrp.addMapping("/*");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建springMVC应用上下文
     * @param servletContext
     * @return
     */
    public  WebApplicationContext createApplicationContext(
            ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    public static void main(String[] args) {
        new Main3();
    }
}
